package com.hanxu.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;


/**
 * aop的思想
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    /**授权
     * 首页所有人可以访问，功能也对应的权限才能访问
     * @param http
     * @throws Exception
     * 请求权限规则
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //请求授权规则
        http.authorizeRequests().
                antMatchers("/").permitAll().
                antMatchers("/level1/**").hasRole("vip1").
                antMatchers("/level2/**").hasRole("vip2").
                antMatchers("/level3/**").hasRole("vip3");


        //没有权限会默认跳转到首页
        http.formLogin();

        //关闭csrf攻击功能
        http.csrf().disable();

        //注销功能开启  成功就调到主页
        http.logout() ;
    }


    /**
     * 认证
     * @param auth
     * @throws Exception
     * 从内存中读取登陆页面的账号密码 并且需要密码加密
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //连接数据库的认证方式
        //auth.jdbcAuthentication().dataSource().withUser()

        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("han").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2").and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");
    }
}
